import { Component, Inject, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import {  startOfDay } from 'date-fns';
import { NzMessageService, NzModalService, NzUploadFile } from 'ng-zorro-antd';
import { Observable, Observer } from 'rxjs';
import { LivelibService } from 'src/app/service/livelib.service';
import { API_CONFIG } from 'src/app/service/service.module';
import { DomSanitizer } from '@angular/platform-browser';
import { CustomService } from 'src/app/service/custom.service';
import { ossUri } from 'src/app/service/action_type';
import { Router } from '@angular/router';

@Component({
  selector: 'app-live-lib',
  templateUrl: './live-lib.component.html',
  styleUrls: ['./live-lib.component.less']
})
export class LiveLibComponent implements OnInit {

  datalist: any[] | null = null;
  isLoading: boolean = false;
  totalCount: number = 0;
  selectData: any = {
    status: 0,
    pagesize: 10,
    pageindex: 1
  };
  isCreateShow: boolean = false;
  validateForm!: FormGroup;
  logoUrl?: string;
  ossUrl: string = ossUri;
  logo: string | null = null;
  loading = false;
  uploadUrl: string | null = '';
  headers: any | null = null;
  maxLiveRoomCount: number = 0;

  disabledDate = (current: Date): boolean => {
    let today = startOfDay(new Date());
    return current < today;
  };

  beforeUpload = (file: NzUploadFile, _fileList: NzUploadFile[]) => {
    return new Observable((observer: Observer<boolean>) => {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
      if (!isJpgOrPng) {
        this.msg.error('只能上传图片!');
        observer.complete();
        return;
      }
      const isLt2M = file.size! / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.msg.error('图片必须小于 2MB!');
        observer.complete();
        return;
      }
      observer.next(isJpgOrPng && isLt2M);
      observer.complete();
    });
  };

  handleChange(info: { file: NzUploadFile }): void {
    switch (info.file.status) {
      case 'uploading':
        this.loading = true;
        break;
      case 'done':
        // Get this url from response in real world.
        this.logo = info.file.response.name;
        this.logoUrl = info.file.response.url;
        this.loading = false;
        break;
      case 'error':
        this.msg.error('Network error');
        this.loading = false;
        break;
    }
  }

  submitForm() {
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }
    if (this.validateForm.status == "VALID") {
      var data = this.validateForm.value;
      if (data.liveDate && data.liveDate.length > 1) {
        data['startDate'] = data.liveDate[0];
        data['endDate'] = data.liveDate[1];
      }
      if (this.logo) {
        data['logo'] = this.logo;
      }
      this.livelibService.save(data).subscribe(result => {
        if (result['code'] === 'success') {
          this.validateForm.reset();
          for (const key in this.validateForm.controls) {
            this.validateForm.controls[key].markAsPristine();
            this.validateForm.controls[key].updateValueAndValidity();
          }
          this.isCreateShow = false;
          this.getlist();
          this.modalService.success({
            nzTitle: '信息提示',
            nzContent: '您的直播创建成功!'
          });
        }
        else {
          this.modalService.error({
            nzTitle: '信息提示',
            nzContent: result['data']
          });
        }
      });
    }
  }

  createClose() {
    this.isCreateShow = false;
  }

  createOpen() {
    this.isCreateShow = true;
  }

  checkOnline() {
    this.livelibService.getOnlineLive().subscribe(result => {
      let onlineInfo = result['data']['OnlineInfo'];
      if (onlineInfo) {
        let streamInfo: any[] = onlineInfo.LiveStreamOnlineInfo;
        this.datalist.forEach(item => {
          let thisLive = streamInfo.find(w => w.StreamName === item['roomId']);
          if (thisLive)
            item['status'] = 1;
          else
            item['status'] = 0;
        });
      }
    });
  }

  getlist() {
    this.isLoading = true;
    this.livelibService.page(this.selectData).subscribe(result => {
      this.isLoading = false;
      this.totalCount = result['data']['count'];
      this.datalist = result['data']['items'];
      this.checkOnline();
    });
  }

  goDetail(id: number) {
    this.router.navigateByUrl(`/main/live/detail/${id}`);
  }

  constructor(
    private msg: NzMessageService,
    private fb: FormBuilder,
    private livelibService: LivelibService,
    private modalService: NzModalService,
    private customService: CustomService,
    private router: Router,
    @Inject(API_CONFIG) private uri: string,
    private sanitizer: DomSanitizer
  ) {
    //this.iframeUrl = this.sanitizer.bypassSecurityTrustResourceUrl('#'); 
  }

  ngOnInit(): void {
    this.uploadUrl = this.uri + '/custom/upload/live-cover';
    let ticket = window.sessionStorage['ticket'];
    this.headers = { 'Authorization': 'BasicAuth ' + ticket };
    this.getlist();
    this.customService.profile().subscribe(result => {
      this.maxLiveRoomCount = result['data']['maxLiveRoomCount'];
    });
    this.validateForm = this.fb.group({
      title: [null, [Validators.required]],
      liveDate: [null, [Validators.required]],
      introduce: [null, [Validators.required]]
    });
  }
}
